<template>
  <div id="listQuestionSubmitView">
    <!--搜索题目提交记录-->
    <a-form :model="searchParams" layout="inline" class="searchQuestionForm">
      <a-form-item field="title" label="题号" tooltip="精确匹配">
        <a-input
          v-model="searchParams.questionId"
          placeholder="请输入题号"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="userAccount" label="提交者" tooltip="精确匹配">
        <a-input
          v-model="searchParams.userAccount"
          placeholder="请输入用户账号"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="status" label="判题结果">
        <a-select
          :style="{ width: '180px' }"
          v-model="searchParams.judgeResult"
          placeholder="请选择判题结果"
          allow-clear
        >
          <a-option value="Accepted">答案正确</a-option>
          <a-option value="Compile_Error">编译错误</a-option>
          <a-option value="Wrong_Answer">答案错误</a-option>
          <a-option value="Memory_Limit_Exceeded">内存溢出</a-option>
          <a-option value="Time_Limit_Exceeded">超时</a-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button
          type="outline"
          shape="round"
          status="normal"
          @click="doSearch"
        >
          搜索
        </a-button>
      </a-form-item>
      <a-button
        type="outline"
        shape="round"
        status="success"
        @click="refreshJudgeStatus"
        >刷新
      </a-button>
    </a-form>

    <!--题目表格-->
    <a-table
      :columns="columns"
      :data="data"
      :pagination="pagination"
      @page-change="onPageChange"
      column-resizable
      filter-icon-align-left
    >
      <!--判题信息-->
      <template #judgeInfo="{ record }">
        <a-tag
          v-if="record.judgeInfo.message != 'Accepted'"
          class="tagsList"
          color="red"
        >
          {{ record.judgeInfo.message }}
        </a-tag>
        <a-tag v-else class="tagsList" color="green">
          {{ record.judgeInfo.message }}
        </a-tag>
        <a-tag
          v-if="record.judgeInfo.memory != null"
          class="tagsList"
          color="orange"
          >内存：{{ record.judgeInfo.memory }} KB
        </a-tag>
        <a-tag
          v-if="record.judgeInfo.time != null"
          class="tagsList"
          color="blue"
          >耗时：{{ record.judgeInfo.time }} MS
        </a-tag>
      </template>

      <!--创建时间-->
      <template #createTime="{ record }">
        {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>

      <!--提交号-->
      <template #submitId="{ record }">
        <a-link @click="getQuestionSubmitInfo(record.id)">
          {{ record.id }}
        </a-link>
      </template>

      <!--题号-->
      <template #questionId="{ record }">
        <a-link @click="toDoQuestion(record.questionId)">
          {{ record.questionId }}
        </a-link>
      </template>

      <!--判题状态-->
      <template #status="{ record }">
        <a-tag v-if="record.status == 0" color="gray">待判题</a-tag>
        <a-tag v-else-if="record.status == 1" color="gold">判题中</a-tag>
        <a-tag v-else-if="record.status == 2" color="blue">已完成</a-tag>
        <a-tag v-else color="red">失败</a-tag>
      </template>
    </a-table>

    <!--抽屉-->
    <a-drawer
      :width="500"
      :visible="submitDrawerVisible"
      @ok="handleSubmitDrawerOk"
      @cancel="handleSubmitDrawerCancel"
      unmountOnClose
    >
      <template #title>您提交的答案</template>
      <Editor :value="submitDrawerContent" mode="tab" />
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from "vue";
import { QuestionControllerService } from "../../../generated";
import { Message } from "@arco-design/web-vue";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import { useRouter } from "vue-router";
import { Editor } from "@bytemd/vue-next";

const router = useRouter();

// 表格列
const columns = [
  {
    slotName: "submitId",
    title: "提交号",
    align: "center",
  },
  {
    slotName: "questionId",
    title: "题号",
    align: "center",
  },
  {
    dataIndex: "userVO.userName",
    title: "提交者",
    align: "center",
    // ellipsis: true,
  },
  {
    slotName: "judgeInfo",
    title: "结果",
    align: "center",
  },
  {
    dataIndex: "language",
    title: "编程语言",
    align: "center",
  },
  {
    slotName: "status",
    title: "判题状态",
    align: "center",
  },
  {
    slotName: "createTime",
    title: "创建时间",
    align: "center",
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
  },
];
// 数据列表
const data = ref([]);

// 搜索表单
const searchParams = ref({
  current: 1,
  pageSize: 9,
  questionId: null,
  userAccount: null,
  judgeResult: null,
  sortField: "createTime",
  sortOrder: "descend",
});

// 分页结果参数
let pagination = reactive({
  showTotal: true,
  current: 0,
  pageSize: 0,
  total: 0,
});

// 加载数据
const loadData = async () => {
  const res =
    await QuestionControllerService.listQuestionSubmitVoByPageUsingPost(
      searchParams.value as any
    );
  if (res.code === 0) {
    // 数据赋值
    data.value = res.data.records;
    // 分页结果参数赋值
    pagination.total = Number(res.data.total);
    pagination.current = Number(res.data.current);
    pagination.pageSize = Number(res.data.size);
  } else {
    Message.error("获取数据失败，" + res.message);
  }
};

/**
 * 搜索
 */
const doSearch = () => {
  // 这里需要重置页号，不然你在第二页搜索第一页的内容，会搜不到
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

/**
 * 监听 () => { } 中的内容，
 * 内容中的变量（例如searchParams）发生改变时会再次触发() => { }中的内容（即loadData()重新加载数据）
 */
watchEffect(() => {
  loadData();
});

/**
 * 页码改变时触发
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 做题按钮
 * @param questionId 题目id
 */
const toDoQuestion = (questionId: number) => {
  router.push({
    path: `/question/doQuestion/${questionId}`,
  });
};

/**
 * 获取题目提交信息
 */
const submitDrawerContent = ref();
const submitDrawerVisible = ref(false);

const handleSubmitDrawerOk = () => {
  submitDrawerVisible.value = false;
};
const handleSubmitDrawerCancel = () => {
  submitDrawerVisible.value = false;
};

const getQuestionSubmitInfo = async (questionId: number) => {
  // 如果没登陆，调整登录页面
  if (!localStorage.getItem("token")) {
    await router.push({
      path: "/user/login",
    });
    return;
  }
  submitDrawerVisible.value = true;
  const res = await QuestionControllerService.getQuestionSubmitByIdUsingGet(
    questionId
  );
  if (res.code === 0) {
    submitDrawerContent.value = res.data?.code;
  } else {
    Message.error("获取题目提交信息失败，" + res.message);
  }
};

/**
 * 刷新判题状态
 */
const refreshJudgeStatus = () => {
  loadData();
  Message.success("刷新成功，努力判题中，请耐心等待~");
};
</script>

<style scoped>
#listQuestionSubmitView {
  /*当内容少时，让内容更居中*/
  max-width: 1280px;
  margin: auto;
}

/*标签列表*/
.tagsList {
  margin: 3px;
}

/*搜索题目表单*/
.searchQuestionForm {
  justify-content: center;
  align-content: center;
  margin-bottom: 20px;
}
</style>
